package com.info3k.client.commands.location;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.Button;
import com.info3k.client.Info3K;
import com.info3k.client.commands.event.EditEventCommand;
import com.info3k.client.commands.event.NewEventCommand;
import com.info3k.client.components.GlassDialogBox;
import com.info3k.client.components.LocationListWithSearch;
import com.info3k.client.components.LocationRenderer;
import com.info3k.client.domain.Location;
import com.info3k.client.utils.ToolsClient;


public class SelectLocationCommand extends GlassDialogBox implements Command { 
	
	private LocationListWithSearch locationList;
	
	private Command command;
	
	private Info3K info3k;

	public SelectLocationCommand(Command cmd, Info3K info){
		this.info3k = info;
		setCommand(cmd);
		panel.setSize("550px", "450px");
		
		Location[] locations = null;
		if(command instanceof NewEventCommand)
			locations = ((NewEventCommand)command).getLocations();
		else if(command instanceof EditEventCommand)
			locations = ((EditEventCommand)command).getLocations();
		
		locationList = new LocationListWithSearch(true, info3k, null, null, "350px", locations);
		content.add(locationList);
		
		setText(Info3K.msgs.selectLocations());
		
		Button okButton = new Button(Info3K.msgs.ok());
		footer.add(okButton);
		
		okButton.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				hideExtend();
			}
		});
	}

	public void execute() {
		center();
	}
	
	public void hideExtend() {
		List<Location> selectedLocations = new ArrayList<Location>();
		if(locationList.getLocationRenderers()!=null){
			for (LocationRenderer renderer : locationList.getLocationRenderers()) {
				if(renderer.isLocationSelected()){
					selectedLocations.add(renderer.getLocation());
				}
			}
		}
		
		if(command instanceof NewEventCommand)
			((NewEventCommand)command).setLocations(ToolsClient.fromCollectionToArray(selectedLocations, new Location[selectedLocations.size()]));
		else if(command instanceof EditEventCommand)
			((EditEventCommand)command).setLocations(ToolsClient.fromCollectionToArray(selectedLocations, new Location[selectedLocations.size()]));
		hide();
	}

	public void setCommand(Command command) {
		this.command = command;
	}

	public Command getCommand() {
		return command;
	}	
}